// 分类模型
const { CategoryOne, CategoryTwo, CategoryThree } = require('../../../models/category');
// 统一数据返回类
const { DataReturn } = require('../../../common/returnclass');

/**
 * @api {Delete} /categories/:id/:level 删除分类
 * @apiGroup Admin-Categories
 *
 * @apiParam {ObjectId} id 商品分类id
 * @apiParam {String} level 分类等级
 *
 * @apiSuccess {Number} code 状态码
 * @apiSuccess {Object} data 返回数据
 * @apiSuccess {String} msg  返回消息
 */
module.exports = async (req, res) => {
	// 商品分类_id
	let { id, level } = req.params;
	let result;
	
	if (level == 1) {
		
		result = await CategoryOne.findOne({  _id: id })
		if (result) {
			// 下级id
			let lowerIdList = result.children;
			// 第一层
			CategoryOne.findOneAndDelete({ _id: id })
			.then(()=>{
				// 第二层
				lowerIdList.forEach(async item=>{
					let res = await CategoryTwo.findOne({  _id: item })
					res.children.forEach(async items =>{
						await CategoryThree.findOneAndDelete({ _id: items })
					})
					 await CategoryTwo.findOneAndDelete({ _id: item })
				})
				DataReturn.getData(res, 200 ,[], '删除成功')
			}).catch((err)=>{
				DataReturn.getData(res, 400, [], '删除失败')
			})
			return;
		}
		DataReturn.getData(res, 200, [], '该数据不存在');
		
	} else if (level == 2) {
		
		result = await CategoryTwo.findOne({  _id: id })
		if (result) {
			// 下级id
			let lowerIdList = result.children;
			CategoryTwo.findOneAndDelete({ _id: id })
			.then(()=>{
				lowerIdList.forEach(async item=>{
					await CategoryThree.findOneAndDelete({ _id: item })
				})
				DataReturn.getData(res, 200 ,[], '删除成功')
			}).catch((err)=>{
				DataReturn.getData(res, 400, [], '删除失败')
			})
			return;
		}
		DataReturn.getData(res, 200, [], '该数据不存在');
		
	} else if (level == 3) {
		
		result = await CategoryThree.findOne({  _id: id })
		if (result) {
			 CategoryThree.findOneAndDelete({ _id: id })
			.then(()=>{
				DataReturn.getData(res, 200 ,[], '删除成功')
			}).catch((err)=>{
				DataReturn.getData(res, 400, [], '删除失败')
			})
			return;
		}
		DataReturn.getData(res, 200, [], '该数据不存在');
		
	}
}